package com.audio.controller;

import com.audio.mapper.UserMapper;
import com.audio.pojo.dto.TaskDTO;
import com.audio.pojo.entity.Log;
import com.audio.result.Result;
import com.audio.service.FileService;
import com.audio.service.impl.FileServiceImpl;
import com.audio.websocket.AudioProcessingWebSocketHandler;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/audio")
public class AudioController {

    @Resource
    private FileService fileService;
    @Resource
    private AudioProcessingWebSocketHandler webSocketHandler;
    @Resource
    private UserMapper userMapper;

    @PostMapping("/task")
    public Result task(TaskDTO taskDTO) {
        int id_role = userMapper.getId_Role(1L);
        if (id_role == 0) {
            return Result.error("使用次数不足，请联系管理员");
        }
        userMapper.updateUserRole(1L);

        String taskId = UUID.randomUUID().toString();
        String message =taskId;
        MultipartFile file = taskDTO.getMultipartFile();
        log.info("接收到文件进行处理：{}", file.getName());

        // 将文件保存在本地
        File localFile = FileServiceImpl.saveFile(file);
        // 立即响应
        new Thread(() -> {
            // 异步调用处理方法，启动后台任务
            fileService.deal(taskDTO, webSocketHandler, taskId, localFile);
        }   ).start();
        return Result.success(message);
    }

    @GetMapping("/log")
    public Result<List<Log>> log() {
        List<Log> log1 = userMapper.getLog(1L);
        //Page<Log> pages = userMapper.getLog(1L);
        return Result.success(log1);
    }
}
